<template>
  <div v-elclickoutside="handleClose" ref="reference" id="wkDepSelectId"
       :class="[disabled ? 'is_disabled' : 'is_valid', { 'is_focus': visible }]"
       wrap="wrap"
       class="wk-dep-select "
       @dblclick="containerClick">
    <div class="user-placeholder  text-one-line">
      <template v-for="(item, index) in showSelectedListWithLimit" :key="index">
        <span class="user-item text-one-line" style="color:#606266 ">
          {{ item.name }}
          <el-icon @click.stop="deleteDept(index)"><Close/></el-icon>
      </span>
      </template>
    </div>
    <el-icon v-if="selectedList.length > showMaxCount">
      <MoreFilled/>
    </el-icon>
    <span class="el-icon-arrow-up">
      <el-icon v-if="visible"><ArrowDown/></el-icon>
      <el-icon v-else><ArrowUp/></el-icon>
    </span>
    <div v-if="selectedList.length == 0" class="user-placeholder text-one-line">{{ placeholder }}</div>
    <WkSelectDropdown v-if="visible && !disabled">
      <template v-slot:default>
        <el-scrollbar ref="scrollbar" tag="div">
          <WkDep :disabled="disabled" :radio="radio"
                 v-model:deptSelectedList="deptSelectedList"
                 :optionsDeptList="optionsDeptList"
                 :props="config"/>
        </el-scrollbar>
      </template>
    </WkSelectDropdown>
  </div>

</template>

<script setup>
import WkSelectDropdown from './src/SelectDropdown.vue'
import WkDep from './src/WkDep.vue'
import {valueEquals} from '/src/utils/elementui.js'
import {objDeepCopy} from '/src/utils/index.js'
import merge from '/src/utils/merge.js'
import {useErpUserStore} from "../../../../store/modules/usererp.js";
import {useHrmStore} from "@/store/modules/hrm.js";

const DefaultWkDepSelect = {
  value: 'id',
  label: 'name',
  dataType: 'manage', // 部门的 value label 一致，用 dataType 区分
  isList: false // 默认是树形接口，如果是列需设置为true。好像没有使用
}

defineOptions({
  name: 'WkDepSelect',
})

// 是否单选、最多展示格式
// placeholder
// deptSelected、optionsDeptList
const props = defineProps({
  // 是否单选
  radio: {
    type: Boolean,
    default: true
  },
  // 展示限制
  showMaxCount: {
    type: Number,
    default: 2
  },
  placeholder: {
    type: String,
    default() {
      return '请选择'
    }
  },
  // eslint-disable-next-line vue/require-prop-types
  // 已经选择的部门
  deptSelected: {
    required: true
  },
  // 通过外部设置部门列表，如果这里设置了，那么在wkDept中就不在调用接口获取部门数据
  optionsDeptList: Array,
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
})

const emits = defineEmits({
  'visible-change': null,
  'update:deptSelected': null,
})

// 本地数据
const optionData = reactive({
  visible: false,
  deptSelectedList: [], // 校准传入值
})
const {visible, deptSelectedList,} = toRefs(optionData)

// 合并 props
const config = computed(() => {
  console.log("configProps", DefaultWkDepSelect)
  return DefaultWkDepSelect
})


// 获取deptList数据
const deptList = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.deptList
})
// 获取hrmDeptList数据
const hrmDeptList = computed(() => {
  const erpUserStore = useHrmStore();
  return erpUserStore.hrmDeptList
})

const allDeptList = computed(() => {
  // 如果类型是管理，获取deptList中的数据
  if (config.value.dataType === 'manage') {
    // 以缓存中的全部数据为id转对象的源
    return deptList.value
  } else if (config.value.dataType === 'hrm') {
    // 如果类型是hrm，获取hrmDeptList中的数据
    return hrmDeptList.value
  }
})

// 选择的数据，页面的显示需要根据他的长度判断
const selectedList = computed(() => {
  if (!allDeptList.value.length) {
    return []
  }
  return getSelectedList()
})

/**
 * 获取展示的数组
 */
function getSelectedList() {
  const list = []
  recursionOptions(allDeptList.value, optionData.deptSelectedList, list)
  return list
}


function recursionOptions(deptList, selectedList, targetList) {
  deptList.forEach(item => {
    if (selectedList.includes(item[config.value.value])) {
      targetList.push(item)
    }
    // 如果有子部门，继续查询子部门
    if (item.children) {
      recursionOptions(item.children, selectedList, targetList)
    }
  })
}

// 实际展示的数据。它根据selectedList的数据来判断。主要判断长度是否超过showMaxCount
const showSelectedListWithLimit = computed(() => {
  if (selectedList.value && selectedList.value.length > props.showMaxCount) {
    return selectedList.value.slice(0, props.showMaxCount)
  }
  return selectedList.value
})


watch(visible, (val) => {
  emits('visible-change', val)
})

// 如果传入的已选择的部门列表改变了，执行重新验证数据的功能
watch(() => props.deptSelected, (val) => {
  verifyValue()
})

function created() {
  verifyValue()
  requestDepList()
}
created()


/**
 * 处理值逻辑
 */
function verifyValue() {
  // 多选的默认值 校准为数组  单选校准为number
  if (!props.radio && !Array.isArray(props.deptSelected)) {
    emits('update:deptSelected', [])
  }

  if (props.radio && (Array.isArray(props.deptSelected) || props.deptSelected === null || props.deptSelected === undefined)) {
    emits('update:deptSelected', '')
  }

  if (props.radio) {
    // 如果是单选
    if (props.deptSelected !== optionData.deptSelectedList) {
      if (props.deptSelected) {
        optionData.deptSelectedList = [parseInt(props.deptSelected)]
      } else {
        optionData.deptSelectedList = []
      }
    }
  } else {
    if (!valueEquals(props.deptSelected, optionData.deptSelectedList)) {
      if (props.deptSelected && props.deptSelected.length) {
        const firstItem = props.deptSelected[0]
        if (firstItem[config.value.value]) {
          optionData.deptSelectedList = props.deptSelected.map(item => item[config.value.value])
        } else {
          optionData.deptSelectedList = objDeepCopy(props.deptSelected)
        }
      } else {
        optionData.deptSelectedList = []
      }
    }
  }
}


/**
 * 获取请求
 */
function requestDepList() {
  if (config.value.dataType === 'manage') {
    // 以缓存中的全部数据为id转对象的源
    const erpUserStore = useErpUserStore()
    erpUserStore.debounceGetDeptList()
  } else if (this.config.dataType === 'hrm') {
    const erpUserStore = useHrmStore()
    erpUserStore.debounceGetHrmDeptList()
  }
}



function handleClose() {
  optionData.visible = false
}


/**
 * 删除
 */
function deleteDept(index) {
  if (!props.disabled) {
    // 直接 splice ,deptSelectedList watch 的老旧值相同，复制之后新旧值不相同。暂时解决
    const selectedList = objDeepCopy(optionData.deptSelectedList)
    selectedList.splice(index, 1)
    optionData.deptSelectedList = selectedList
  }
}

function containerClick() {
  if (!props.disabled) {
    optionData.visible = !optionData.visible
  }
}
</script>

<style lang="scss" scoped>
.wk-dep-select {
  height: 34px;
  position: relative;
  border-radius: 4px;
  font-size: 13px;
  background-color: white;
  border: 1px solid #e6e6e6;
  color: #333333;
  width: 180px;
  padding: 0 20px 0 5px;
  cursor: pointer;

  .user-item {
    padding: 5px 15px 5px 5px;
    background-color: #F3F7FF;
    border-radius: 4px;
    margin: 3px;
    max-width: 80px;
    position: relative;
  }

  .user-placeholder {
    color: #ddd;
    line-height: 34px;
    cursor: pointer;
    user-select: none;
  }

  .delete-icon {
    color: #999;
    cursor: pointer;
    position: absolute;
    top: 8px;
    right: 2px;

    &:hover {
      color: #2362FB;
    }
  }

  &:hover {
    border-color: #c0c4cc;
  }
}

.wk-dep-select.is_disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;

  .user-item {
    background-color: #f0f4f8ea;
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .delete-icon {
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .user-placeholder {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.wk-dep-select.is_valid:hover {
  border-color: #c0c4cc;
}

.wk-dep-select.is_focus {
  border-color: #2362FB !important;
}

.el-icon-more {
  position: absolute;
  top: 5px;
  right: 20px;
  padding: 6px 10px;
  font-size: 12px;
  background-color: #F3F7FF;
  color: #666;
  border-radius: 4px;

  &:hover {
    background-color: #2362FB;
    color: white;
  }
}

.el-icon-arrow-up {
  position: absolute;
  top: 10px;
  right: 5px;
  transition: transform .3s;
  color: #c0c4cc;
  font-size: 14px;
  transition: transform .3s;
  transform: rotate(180deg);
  cursor: pointer;
}

.el-icon-arrow-up.is-reverse {
  transform: rotate(0deg);
}

.el-select__tags {
  padding-right: 30px;
}

// 文本
.text-one-line {
  // text-overflow: ellipsis;
  // display: -webkit-box;
  // -webkit-line-clamp: 1;
  // -webkit-box-orient: vertical;
  // overflow: hidden;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
